﻿#region Copyright ©2008-2009, Technische Universitaet Muenchen
// ====================================================================================================
//
// Last Changed by       $Author: then $
// Last Changed Date     $LastChangedDate: 2009-05-16 14:58:56 +0200 (Sat, 16 May 2009) $
// Last Changed Revision $Rev: 144 $
//
// ====================================================================================================
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Tum.CollabXT.TFS.Resources;


namespace Tum.CollabXT.TFS
{
    public class TFSToolProvider : IToolProvider
    {
        private IProcessProvider ProcessProvider;


        /// <summary>
        /// Gets the log used with this provider.
        /// </summary>
        public Log ProcessLog
        {
            get { return _Log; }
        }
        private Log _Log;

        /// <summary>
        /// Gets or sets the output path.
        /// </summary>
        public string OutputPath
        {
            get { return _OutputPath; }
            set { _OutputPath = value; }
        }
        private string _OutputPath;

        /// <summary>
        /// Gets or sets the template path.
        /// </summary>
        public string TemplatePath
        {
            get { return _TemplatePath; }
            set { _TemplatePath = value; }
        }
        private string _TemplatePath;

        /// <summary>
        /// Gets or sets the path of needed SharePoint files.
        /// </summary>
        public string SharePointDumpPath
        {
            get { return _SharePointDumpPath; }
            set { _SharePointDumpPath = value; }
        }
        private string _SharePointDumpPath;

        /// <summary>
        /// Gets a dictionary of localized strings to be used within the provider.
        /// </summary>
        public Dictionary<string, string> LanguageDictionary
        {
            get { return _LanguageDictionary; }
        }
        private Dictionary<string, string> _LanguageDictionary;



        #region IToolProvider Members
        public static string GetProviderName()
        {
            return Language.ProviderInfo_Name;
        }

        public static string GetProviderDescription()
        {
            return Language.ProviderInfo_Description;
        }

        public static string GetProviderAuthor()
        {
            return "© 2009 TU München";
        }


        public Dictionary<string, object> ExtendedData
        {
            get
            {
                throw new NotSupportedException();
            }
        }


        public void Initialize(IProcessProvider processProvider, Log log)
        {
            this.ProcessProvider = processProvider;
            this._Log = log;
        }

        public void Process()
        {
            #region Preparations
            if (ProcessProvider == null)
                throw new TFSException("ProcessProvider has not been set. Call Initialize before.");

            if (!Directory.Exists(TemplatePath))
                throw new TFSException("Template folder does not exist");

            if (!_OutputPath.EndsWith("/", StringComparison.OrdinalIgnoreCase) && !_OutputPath.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
                _OutputPath += "/";

            if (!_TemplatePath.EndsWith("/", StringComparison.OrdinalIgnoreCase) && !_TemplatePath.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
                _TemplatePath += "/";

            Directory.CreateDirectory(_OutputPath);
            #endregion

            _Log.AddEntry(Language.Processing_PluginInfo);
            _Log.AddEntry(Language.Processing_Copyright);
            _Log.AddSeperator();

            //Load language file
            _LanguageDictionary = Helper.LoadLanguageDictionary(_TemplatePath + "Language.resources");

            #region Copy template
            _Log.AddEntry(Language.Processing_OutputDirectory);
            //Clean output directory
            try
            {
                Helper.DeleteDirectory(_OutputPath);
            }
            catch
            {
                _Log.AddEntryAndThrowException(Language.Error_DeletingOutputDirectory);
            }

            try
            {
                //Copy template data to output directory
                Helper.CopyDirectory(_TemplatePath + "tpl/", _OutputPath);
                #endregion

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_ProjectTemplate);
                (new ProcessTemplate()).Process(ProcessProvider, this);

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_WorkItems);
                WorkItems workItems = new WorkItems();
                workItems.Process(ProcessProvider, this);

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_Classification);
                (new Classification(workItems.GetIterationPaths())).Process(ProcessProvider, this);

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_GroupsPermissions);
                (new GroupsAndPermissions()).Process(ProcessProvider, this);

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_WSS);
                (new WSS(SharePointDumpPath)).Process(ProcessProvider, this);

                _Log.AddSeperator();
                _Log.AddEntry(Language.Processing_CompletedSuccessfully);
            }
            catch(Exception e)
            {
                throw new TFSException(string.Format(Language.Error_Unexpected, e.Message, e.StackTrace));
            }
        }

        public string GetConfigPageName()
        {
            return "TFSConfigPage.xaml";
        }

        public void Serialize(XmlNode outputParentNode)
        {
            XmlDocument xmlDoc = outputParentNode.OwnerDocument;

            XmlNode settingsNode = xmlDoc.CreateElement("settings");
            outputParentNode.AppendChild(settingsNode);

            XmlAttribute outputPathAttribute = xmlDoc.CreateAttribute("outputPath");
            outputPathAttribute.Value = OutputPath;
            settingsNode.Attributes.Append(outputPathAttribute);

            XmlAttribute templatePathAttribute = xmlDoc.CreateAttribute("templatePath");
            templatePathAttribute.Value = TemplatePath;
            settingsNode.Attributes.Append(templatePathAttribute);

            XmlAttribute wssDumpPathAttribute = xmlDoc.CreateAttribute("wssDumpPath");
            wssDumpPathAttribute.Value = SharePointDumpPath;
            settingsNode.Attributes.Append(wssDumpPathAttribute);
        }

        public void Deserialize(XmlNode inputParentNode)
        {
            XmlNode settingsNode = inputParentNode.SelectSingleNode("settings");

            try
            {
                _OutputPath = null;
                _OutputPath = settingsNode.Attributes["outputPath"].Value;
            }
            catch { }

            try
            {
                _TemplatePath = null;
                _TemplatePath = settingsNode.Attributes["templatePath"].Value;
                if (!Directory.Exists(_TemplatePath))
                    _TemplatePath = null;
            }
            catch { }

            try
            {
                _SharePointDumpPath = null;
                _SharePointDumpPath = settingsNode.Attributes["wssDumpPath"].Value;
                if (!Directory.Exists(_SharePointDumpPath))
                    _SharePointDumpPath = null;
            }
            catch { }
        }

        #endregion
    }
}